const app = getApp();
Page({
  data: {
    recording: false, // 是否正在录制
    cameraContext: null, // 相机上下文
    timer: null, // 定时器
  },

  onLoad: function () {
    console.log(app.globalData);
    this.setData({
      cameraContext: wx.createCameraContext(this),
    });
  },

  startRecording: function () {
    if (this.data.recording) return; // 防止重复录制
    this.data.timer && clearInterval(this.data.timer); // 清除定时器
    console.log('开始录制');
    app.globalData.videoList = [];
    this.setData({ recording: true });
    this.startCapture();
    // 设置定时器每4分钟停止录制
    this.data.timer = setInterval(() => {
      this.stopCapture();
    }, 4 * 60 * 1000); // 4分钟
  },

  stopRecording: function () {
    if (!this.data.recording) return;
    clearInterval(this.data.timer); // 清除定时器
    this.stopCapture(() => {
      wx.setKeepScreenOn({ keepScreenOn: false });
      this.setData({ recording: false }, () => {
        wx.navigateTo({ url: '/demo3/videoList/index' });
      });
    });
  },

  startCapture: function () {
    const cameraContext = this.data.cameraContext;
    cameraContext.startRecord({
      timeout: 5 * 60,
      success: () => {
        wx.setKeepScreenOn({ keepScreenOn: true });
        console.log('Recording started');
      },
      fail: (err) => {
        console.error('Start recording failed', err);
      },
    });
  },

  stopCapture: function (cb) {
    const cameraContext = this.data.cameraContext;
    cameraContext.stopRecord({
      complete: (res) => {
        const tempFilePath = res.tempVideoPath;
        console.log(tempFilePath);
        if (tempFilePath) {
          if (typeof cb !== 'function') {
            setTimeout(() => this.startCapture());
          }
          if (app.globalData.videoList) {
            app.globalData.videoList = [...app.globalData.videoList, tempFilePath];
          } else {
            app.globalData.videoList = [tempFilePath];
          }
        }
        cb && cb();
      },
    });
  },

  gotoPage: function () {
    this.setData({ recording: false }, () => {
      wx.navigateTo({ url: '/demo3/videoList/index' });
    });
  },
});
